//
//  PayViewController.m
//  家校互通
//
//  Created by 姬鑫宇 on 15/6/1.
//  Copyright (c) 2015年 姬鑫宇. All rights reserved.
//

#import "PayViewController.h"
#import <AlipaySDK/AlipaySDK.h>
#import "Order.h"
#import "DataSigner.h"
#import "payRequsestHandler.h"
#import "PayButtonTableViewCell.h"
#import "PayDetailTableViewCell.h"
#import "PayMenberListTableViewCell.h"
#import "UITableView+FDTemplateLayoutCell.h"
@interface PayViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, retain) Product *product;
@property (nonatomic, retain) NSMutableArray *memberListArray;//已经支付的用户
@property (nonatomic, retain) NSMutableArray *btnTitleArray;//支付宝，微信

@property (nonatomic, strong) PaymentDetail *paymentDetail;
@end

@implementation PayViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _product.body = @"支付宝测试内容";
    _product.subject = @"学费";
    _product.price = 120.0;
    _memberListArray=[[NSMutableArray alloc]initWithCapacity:0];
    [_memberListArray addObjectsFromArray:[NSArray arrayWithObjects:@"支付宝",@"微信",@"支付宝",@"微信",@"支付宝",@"微信",@"支付宝",@"微信",@"支付宝",@"微信", nil]];
    _btnTitleArray=[NSMutableArray arrayWithObjects:@"支付宝",@"微信支付", nil];
    
    _contentTableView.delegate=self;
    _contentTableView.dataSource=self;
    [self connect];
    // Do any additional setup after loading the view.
}
-(void)connect
{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [CoModel getPaymentDetail:^(BOOL result, PaymentDetail *paymentDetail, NSError *error) {
        if (result) {
              [MBProgressHUD hideHUDForView:self.view animated:YES];
            _paymentDetail=paymentDetail;
            [_contentTableView reloadData];
        }
    } andPaymentId:_payId];
}
#pragma mark -UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section==0) {
        return 1;
    }else
    {
        if (_hasPayfees) {
            return [_memberListArray count];
        }else
        {
            return _btnTitleArray.count;
        }
    }
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0) {
        PayDetailTableViewCell *vCell=[tableView dequeueReusableCellWithIdentifier:@"PayDetailTableViewCell" forIndexPath:indexPath];
        [vCell setPayModel:_paymentDetail];
        return vCell;
    }
    
    else
    {
        if (_hasPayfees) {
            PayMenberListTableViewCell *vCell=[tableView dequeueReusableCellWithIdentifier:@"PayMenberListTableViewCell" forIndexPath:indexPath];
            UIView *selectView=[[UIView alloc]initWithFrame:vCell.frame];
            selectView.backgroundColor=COLOR(240, 240, 240);
            vCell.selectedBackgroundView=selectView;
            return vCell;
        }else
        {
            PayButtonTableViewCell *vCell=[tableView dequeueReusableCellWithIdentifier:@"PayButtonTableViewCell" forIndexPath:indexPath];
            vCell.payImageView.image=[UIImage imageNamed:[_btnTitleArray objectAtIndex:indexPath.row]];
           
            UIView *selectView=[[UIView alloc]initWithFrame:vCell.frame];
            selectView.backgroundColor=COLOR(240, 240, 240);
            vCell.selectedBackgroundView=selectView;
            return vCell;
        }
      
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
- (UIView *)createHeaderViewWithSection:(NSInteger)section
{
    UIView *headerView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, DSF_SCREENWIDTH, 30)];
    UILabel *titleLB=[[UILabel alloc] initWithFrame:CGRectMake(10, 0, DSF_SCREENWIDTH, 30)];
    if (section==0) {
        titleLB.text=@"缴费详情";
    }else
    {
        if (_hasPayfees) {
            titleLB.text=@"已完成支付列表";
        }else
        {
            titleLB.text=@"选择支付方式";
        }
    }
    [headerView addSubview:titleLB];
    return headerView;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    return [self createHeaderViewWithSection:section];
}
#pragma mark -UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0) {
      return [tableView fd_heightForCellWithIdentifier:@"PayDetailTableViewCell" cacheByIndexPath:indexPath configuration:^(PayDetailTableViewCell *vCell) {
          [vCell setPayModel:_paymentDetail];
      }];
    }
    else
    {
        if (_hasPayfees) {
            return 44;
        }else
        {
            return 50;
        }
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 10;
}
// Called after the user changes the selection.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0) {
     
    }
    else
    {
        NSString *titleString= [_btnTitleArray objectAtIndex:indexPath.row];
        if ([titleString isEqualToString:@"支付宝"]) {
            [self alipayPress:nil];
        }else if ([titleString isEqualToString:@"微信支付"])
        {
            [self weChatPay:nil];
        }
        [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)alipayPress:(id)sender{
    /*
     *点击获取prodcut实例并初始化订单信息
     */
//    Product *product = [self.productList objectAtIndex:indexPath.row];
    
    /*
     *商户的唯一的parnter和seller。
     *签约后，支付宝会为每个商户分配一个唯一的 parnter 和 seller。
     */
    
    /*============================================================================*/
    /*=======================需要填写商户app申请的===================================*/
    /*============================================================================*/
    NSString *partner = @"";
    NSString *seller = @"alipayrisk10@alipay.com";
    NSString *privateKey = @"";
    /*============================================================================*/
    /*============================================================================*/
    /*============================================================================*/
    
    //partner和seller获取失败,提示
    if ([partner length] == 0 ||
        [seller length] == 0 ||
        [privateKey length] == 0)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                        message:@"缺少partner或者seller或者私钥。"
                                                       delegate:self
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
        return;
    }
    
    /*
     *生成订单信息及签名
     */
    //将商品信息赋予AlixPayOrder的成员变量
    Order *order = [[Order alloc] init];
    order.partner = partner;
    order.seller = seller;
    order.tradeNO = [self generateTradeNO]; //订单ID（由商家自行制定）
    order.productName = _product.subject; //商品标题
    order.productDescription = _product.body; //商品描述
    order.amount = [NSString stringWithFormat:@"%.2f",_product.price]; //商品价格
    order.notifyURL =  @"http://www.xxx.com"; //回调URL
    
    order.service = @"mobile.securitypay.pay";
    order.paymentType = @"1";
    order.inputCharset = @"utf-8";
    order.itBPay = @"30m";
    order.showUrl = @"m.alipay.com";
    
    //应用注册scheme,在AlixPayDemo-Info.plist定义URL types
    NSString *appScheme = @"alisdkdemo";
    
    //将商品信息拼接成字符串
    NSString *orderSpec = [order description];
    NSLog(@"orderSpec = %@",orderSpec);
    
    //获取私钥并将商户信息签名,外部商户可以根据情况存放私钥和签名,只需要遵循RSA签名规范,并将签名字符串base64编码和UrlEncode
    id<DataSigner> signer = CreateRSADataSigner(privateKey);
    NSString *signedString = [signer signString:orderSpec];
    
    //将签名成功字符串格式化为订单字符串,请严格按照该格式
    NSString *orderString = nil;
    if (signedString != nil) {
        orderString = [NSString stringWithFormat:@"%@&sign=\"%@\"&sign_type=\"%@\"",
                       orderSpec, signedString, @"RSA"];
        
        [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
            NSLog(@"reslut = %@",resultDic);
        }];
    }

}

- (void)weChatPay:(id)sender{
    //从服务器获取支付参数，服务端自定义处理逻辑和格式
    //订单标题
    NSString *ORDER_NAME    = @"Ios服务器端签名支付 测试";
    //订单金额，单位（元）
    NSString *ORDER_PRICE   = @"0.01";
    
    //根据服务器端编码确定是否转码
    NSStringEncoding enc;
    //if UTF8编码
    //enc = NSUTF8StringEncoding;
    //if GBK编码
    enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
    NSString *urlString = [NSString stringWithFormat:@"%@?plat=ios&order_no=%@&product_name=%@&order_price=%@",
                           SP_URL,
                           [[NSString stringWithFormat:@"%ld",time(0)] stringByAddingPercentEscapesUsingEncoding:enc],
                           [ORDER_NAME stringByAddingPercentEscapesUsingEncoding:enc],
                           ORDER_PRICE];
    
    //解析服务端返回json数据
    NSError *error;
    //加载一个NSURL对象
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    //将请求的url数据放到NSData对象中
    NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    if ( response != nil) {
        NSMutableDictionary *dict = NULL;
        //IOS5自带解析类NSJSONSerialization从response中解析出数据放到字典中
        dict = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];
        
        NSLog(@"url:%@",urlString);
        if(dict != nil){
            NSMutableString *retcode = [dict objectForKey:@"retcode"];
            if (retcode.intValue == 0){
                NSMutableString *stamp  = [dict objectForKey:@"timestamp"];
                
                //调起微信支付
                PayReq* req             = [[PayReq alloc] init];
                req.openID              = [dict objectForKey:@"appid"];
                req.partnerId           = [dict objectForKey:@"partnerid"];
                req.prepayId            = [dict objectForKey:@"prepayid"];
                req.nonceStr            = [dict objectForKey:@"noncestr"];
                req.timeStamp           = stamp.intValue;
                req.package             = [dict objectForKey:@"package"];
                req.sign                = [dict objectForKey:@"sign"];
                [WXApi sendReq:req];
                //日志输出
                NSLog(@"appid=%@\npartid=%@\nprepayid=%@\nnoncestr=%@\ntimestamp=%ld\npackage=%@\nsign=%@",req.openID,req.partnerId,req.prepayId,req.nonceStr,(long)req.timeStamp,req.package,req.sign );
            }else{
                [self alert:@"提示信息" msg:[dict objectForKey:@"retmsg"]];
            }
        }else{
            [self alert:@"提示信息" msg:@"服务器返回错误，未获取到json对象"];
        }
    }else{
        [self alert:@"提示信息" msg:@"服务器返回错误"];
    }

}

- (void)alert:(NSString *)title msg:(NSString *)msg
{
    UIAlertView *alter = [[UIAlertView alloc] initWithTitle:title message:msg delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    
    [alter show];
}

#pragma mark -
#pragma mark   ==============产生随机订单号==============


- (NSString *)generateTradeNO
{
    static int kNumber = 15;
    
    NSString *sourceStr = @"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    NSMutableString *resultStr = [[NSMutableString alloc] init];
    srand((unsigned)time(0));
    for (int i = 0; i < kNumber; i++)
    {
        unsigned index = rand() % [sourceStr length];
        NSString *oneStr = [sourceStr substringWithRange:NSMakeRange(index, 1)];
        [resultStr appendString:oneStr];
    }
    return resultStr;
}



#pragma mark -
#pragma mark   ==============产生订单信息==============

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
